package com.example.demo.service.impl;

import com.example.demo.commen.ResultCode;
import com.example.demo.dao.UserMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.User;
import com.example.demo.service.IUserService;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserByName(String username) {
        User user = userMapper.selectByUsername(username);
        if(user==null){
            throw  new ApplicationException("用户不存在");
        }
        return user;
    }

    @Override
    public void createUser(User user) {

        User user1 = userMapper.selectByUsername(user.getUsername());
        if(user1!=null){
            throw  new ApplicationException("用户已经存在");
        }
        if (user.getGender() == null) {
// 性别赋默认值
            user.setGender((byte) 2);
        }
// 填充默认值
        user.setIsAdmin((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        user.setArticleCount(0);
        user.setState((byte) 0);
       Integer flag =  userMapper.insertSelective(user);

        if(flag!=1){
            throw  new ApplicationException(ResultCode.FAILED.toString());
        }
    }


    @Override
    public boolean login(String username, String password) {
      User user =  userMapper.selectByUsername(username);
        System.out.println(user);
      if(user==null){
          throw new ApplicationException("您登录的用户名不存在-请重新输入");
      }
      String salt = user.getSalt();
        System.out.println("这是数据库存的腌制");
        System.out.println(salt);
      String ciphertext = user.getPassword();
        System.out.println("这是数据库存入的密文"+ciphertext);
      String newCiphertext = MD5Util.md5Last(password,salt);
        System.out.println("这是我们验证的密文"+newCiphertext);
      if(!newCiphertext.equals(ciphertext)){
          throw new ApplicationException("您输入的密码错误-请重新输入");       //这里可以设置密码只能输入三次，三次之后等待60秒

      }
      return true;
    }

    @Override
    public User getUserById(Long id) {
        if(id==null){
            log.info("id为空");
            throw new ApplicationException("传入id为空");
        }

       User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.info("通过id查询后-无此用户");
            throw new ApplicationException("此用户不存在");
        }
        return user;
    }

    @Override
    public void addOneArticleById(Long id) {
            if(id==null||id<=0){
                throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            }
            User user = userMapper.selectByPrimaryKey(id);
            if(id==null||id<=0){
                throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            }
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setArticleCount(user.getArticleCount()+1);
            int flag = userMapper.updateByPrimaryKeySelective(updateUser);
            if(flag!=1){
                throw  new ApplicationException(ResultCode.FAILED.getMessage());
            }
    }

    @Override
    public void subOneArticleById(Long id) {
        if(id==null||id<=0){
            throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(id==null||id<=0){
            throw  new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int flag = userMapper.updateByPrimaryKeySelective(updateUser);
        if(flag!=1){
            throw  new ApplicationException(ResultCode.FAILED.getMessage());
        }
    }


  /*  修改个人信息*/
    @Override
    public void modifyInfo(User user) {

        if(user==null||user.getId()==null||user.getId()<=0){
            throw new ApplicationException("参数校验失败");
        }

        User user1 = userMapper.selectByPrimaryKey(user.getId());
        if(user1==null||user1.getId()<=0){
            throw new ApplicationException("用户不存在");
        }

        //定义一个标志位
        boolean checkAttr = false;   //用来检验我们前端发来的参数同时为空
        //对每一个参数进行校验并赋值

        //新建一个只对传来的几个属性进行修改
        User updateUser  = new User();
        updateUser.setId(user.getId());

        if(user.getUsername()!=null){
            if(!user.getUsername().equals(user1.getUsername())){  //代表要设置的用户名与当前用户名不一样
                User checkUser = userMapper.selectByUsername(user.getUsername());
                if(checkUser!=null){
                    log.info("设置的用户名已经存在");
                    throw  new ApplicationException("该用户名已经存在");
                }
                //走到这代表要设置的用户名是唯一的
                updateUser.setUsername(user.getUsername());
                checkAttr=true;
            }
        }

        if(user.getNickname()!=null){
            if(!user.getNickname().equals(user1.getNickname())){
                updateUser.setNickname(user.getNickname());
                checkAttr=true;
            }
        }

        if(user.getGender()!=null){
            if(user.getGender()<0||user.getGender()>2){
                user.setGender((byte) 2);
            }
            if(user.getGender()!=user1.getGender()){
                updateUser.setGender(user.getGender());
                checkAttr=true;
            }
        }

        if(user.getEmail()!=null){
            if(!user.getEmail().equals(user1.getEmail())){
                updateUser.setEmail(user.getEmail());
                checkAttr = true;
            }
        }

        if(user.getPhoneNum()!=null){
            if(!user.getPhoneNum().equals(user1.getPhoneNum())){
                updateUser.setPhoneNum(user.getPhoneNum());
                checkAttr=true;
            }
        }
        if(user.getRemark()!=null){
            if(!user.getRemark().equals(user1.getRemark())){
                updateUser.setRemark(user.getRemark());
                checkAttr = true;
            }
        }

        if(checkAttr==false){
            throw new ApplicationException("您设置的修改无变化");
        }

      int row =  userMapper.updateByPrimaryKeySelective(updateUser);

        if(row!=1){
            throw new ApplicationException("更新失败");
        }
    }

    @Override
    public void updatePassword(String Password, String newPassword,Long userId) {

        if (Password == null || !StringUtils.hasLength(Password) || newPassword == null || !StringUtils.hasLength(newPassword)
    ||userId==null||userId<=0){
            throw new ApplicationException("参数校验失败");
        }
        if(Password.equals(newPassword)){
            throw  new ApplicationException("修改的密码与原密码相同");
        }
        User user = userMapper.selectByPrimaryKey(userId);
        if(user==null||user.getId()<=0||user.getDeleteState()==1){
            throw new ApplicationException("用户不存在");
        }

        String salt = UUIDUtil.UUId_32();     //随机生成一个盐

        String encryptPassword = MD5Util.md5Last(newPassword,salt);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setPassword(encryptPassword);
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());
       int flag =  userMapper.updateByPrimaryKeySelective(updateUser);
       if(flag!=1){
           throw  new ApplicationException(ResultCode.FAILED.toString());
       }
       log.info("修改密码成功");

    }
}
